﻿using System.Collections.Generic;
using Lucid.ESA.ClientDataSystem.Domain.Common;
using NHibernate;
using NHibernate.ByteCode.Castle;

namespace Lucid.ESA.ClientDataSystem.Data.Common
{
    /// <summary>
    /// Repository: base repository for persisting an entity.
    /// </summary>
    public class Repository<T> : IRepository<T>
    {
        /// <summary>
        /// This reference does nothing except make sure NHibernate.ByteCode.Castle 
        /// is copied.
        /// </summary>
        private static ProxyFactoryFactory _pff;

        /// <summary>
        /// Saves an entity if it is new, or updates it if it is old.
        /// </summary>
        /// <param name="obj">The entity to save or update.</param>
        public virtual void SaveOrUpdate(T obj)
        {
            SessionProvider.GetCurrentSession().SaveOrUpdate(obj);
        }

        /// <summary>
        /// Saves an entity.
        /// </summary>
        /// <param name="obj">The entity to save.</param>
        public virtual void Save(T obj)
        {
            SessionProvider.GetCurrentSession().Save(obj);
        }

        /// <summary>
        /// Updates an entity.
        /// </summary>
        /// <param name="obj">The entity to update.</param>
        public virtual void Update(T obj)
        {
            SessionProvider.GetCurrentSession().Update(obj);
        }

        /// <summary>
        /// Gets the entity with the specified ID.
        /// </summary>
        /// <param name="id">The ID of the entity to return.</param>
        /// <returns>The entity with the specified ID.</returns>
        public virtual T GetById(long id)
        {
            return SessionProvider.GetCurrentSession().Get<T>(id);
        }

        /// <summary>
        /// Loads a proxy for an entity with the specified ID.
        /// </summary>
        /// <param name="id">The ID of the proxy of the entity to return.</param>
        /// <returns>A proxy of the entity with the specified ID.</returns>
        public virtual T LoadById(long id)
        {
            return SessionProvider.GetCurrentSession().Load<T>(id);
        }

        /// <summary>
        /// Gets all entities.
        /// </summary>
        /// <returns>List of all entities.</returns>
        public virtual List<T> GetAll()
        {
            ICriteria CriteriaQuery = SessionProvider.GetCurrentSession().CreateCriteria(typeof(T));
            return (List<T>)CriteriaQuery.List<T>();
        }
    }
}

